<?php
/**
 * MYSQL数据库操作类
 * @author andery <andery@foxmail.com>
 * @link http://www.minophp.com/
 * @version $Id: CMysql.php 2010-12-17 04:12:44Z andery $
 */
class CMysql implements Ischeme
{    
    protected $version = '';
    protected $_link_id = null;
    protected $_query_count = 0;
    private $_query;
    
    /**    * 构造函数 实现链接数据库功能
    * @access private
    * @param array
    * @return string
    */
    public function __construct($config)
    {
        $db_url = parse_url($config['db_url']);
        if (empty($db_url['pass'])) {
            $db_url['pass'] = '';
        } else {
            $db_url['pass'] = urldecode($db_url['pass']);
        }
        $db_url ['user'] = urldecode($db_url['user']);
    
        if (empty($db_url['path'])) {
            throw new CException(Nimo::lang('no_dbtype_config'));
        } else {
            $db_url['path'] = str_replace('/', '', $db_url['path']);
        }

        $config['charset'] = str_replace('-', '', $config['charset']);
        if (empty($config['charset'])) $config['charset'] = 'utf8';
        $conn_config = array_merge($config, $db_url);
        return $this->connect($conn_config);
    }
    
    /**
     * 连接数据库方法
     * @access public
     * @param array $config
     *   $config['host']   数据库主机名
     *   $config['user']   数据库用户名
     *   $config['pw']     数据库密码
     *   $config['path']   数据库名
     *   $config['charset']  数据库字符集
     *   $config['pconnect'] 持久链接,1为开启,0为关闭
     */
    public function connect($config)
    {
        if($config['pconnect']){
            $this->_link_id = mysql_pconnect($config['host'], $config['user'], $config['pass']);
        }else{
            $this->_link_id = mysql_connect($config['host'], $config['user'], $config['pass'], true);
        }
        if(!$this->_link_id || !mysql_select_db($config['path'], $this->_link_id)) {
            throw new CDbException($this->getError());
        }
        $this->version = mysql_get_server_info($this->_link_id);
        if ($this->version >= "4.1") {
            mysql_query("SET NAMES '".$config['charset']."'", $this->_link_id);//对字符集进行初始化
        }
        if($this->version >'5.0.1'){
            mysql_query("SET sql_mode=''",$this->_link_id);//设置 sql_model
        }
        return $this->_link_id;
    }
    
    public function query($sql)
    {
        $this->_query_count++;
        if (!($query = mysql_query($sql, $this->_link_id))) {
           throw new CDbException($this->getError());
        }
        return $this->query = $query;
    }
    
    function getAll($sql)
    {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = array();
            while ($row = mysql_fetch_assoc($res)) {
                $arr[] = $row;
            }
            return $arr;
        } else {
            return false;
        }
    }
    
    /**
    * 取得结果集数组形式
    * @access public
    * @param  $query
    * @return array
    */
    public function fetch_array($query, $result_type = MYSQL_ASSOC)
    {
        return mysql_fetch_array($query,$result_type);
    }
    
    /**     * 取得结果集对象形式
     * @access public 
     * @param  $query
     */
    public function fetch_fields($query)
    {
        return mysql_fetch_field($query);
    }
    
    /**
     * 获取操作影响的行数
     * @param  $query
     * @return int 
     */
    public function affected_rows()
    {
        return mysql_affected_rows($this->_link_id);
    }
    
    /**
     * 取得结果集的行数
     * @param  $query
     * @return int 
     */
    public function num_rows()
    {
        return mysql_num_rows($this->query);
    }
    
    /**
     * 取得结果集中字段的个数
     * @param  $query
     * @return int 
     */
    public function num_fields()
    {
        return mysql_num_fields($this->query);
    }
    
    /**
    * 取得最后一次执行的ID
    * @access public
    * @return int
    */
    public function insert_id()
    {
        return mysql_insert_id($this->_link_id);
    }
    
    /**
     * 取得数据库中所有的表
     * @access public
     * @param string $dbname 数据库名
     * @return array $tables
     */
    public function get_tables($dbname='')
    {
        $sql = 'SHOW TABLES ';
        $sql .= !empty($dbname) ? 'FROM '.$dbname : '';
        $result = $this->getAll($sql);
        $tables = array();
        foreach ($result as $key => $val) {
            $tables[$key] = current($val);
        }
        return $tables;
    }
    
    /**    * 获得数据库版本
    * @access public
    * @return string
    */
    public function version()
    {
        return $this->version;
    }
    
    /**
    * SQL安全过滤
    * @access public
    * @param  string $str 要过滤的数据
    * @return string
    */
    public function escape_string($str)
    {
        if (PHP_VERSION >= '4.3') {
            return mysql_real_escape_string($str);
        } else {
            return mysql_escape_string($str);
        }    
    }
    
    /**
     * 取得最近错误信息 返回给异常处理
     * @access public
     * @return array
     */
    public function getError()
    {
        return array('db_type'=>'Mysql','code'=>mysql_errno(),'message'=>mysql_error());
    }

    /**      * 关闭连接
     * @access public
     * @return void
     */
    public function close()
    {
        if (!empty ($this->queryID))
            mysql_free_result($this->queryID);
        if ($this->_link_id && !mysql_close($this->_link_id)) {
            throw new CDbException($this->getError());
        }
        $this->_link_id = null;
    }
}